app.controller('home', function ($scope, $http) {

    //证书
    var token = localStorage.getItem('token');
    if (token) {
        $(".disAndNO").css("display", "none");
    } else {

        $(".content_div").css("opacity","0.1");

        $(".content").css("background","#9296a5");
        $(".content").css("opacity","0.8");
        $(".content_div").attr("key","这个比较简单");
        $(".disAndNO").css("display", "block");

    }


    $('.top_four_tips ul li').click(function () {
        $(this).siblings(".click_div").removeClass("click_div");
        $(this).addClass("click_div");
        $('.content_div').find('.display').removeClass("display").addClass("hidden");
        $('.content_div').find('.tab').eq($(this).index()).removeClass("hidden").addClass("display");
    });
    var off = true;
    var praise = $(".fa-thumbs-o-up");

    praise.click(function () {
        if (praise.off) {
            $(this).css("color", "#fb8d2f");
            $(this).text("已赞");
            praise.off = false;
        } else {
            $(this).css("color", "#282f3c");
            $(this).text("点赞");
            praise.off = true;
        }


    });
    var close = true;

    var heart = $(".collection");
    var content = $(".collection_span");
    heart.click(function () {
        if (heart.close) {
            $(this).removeClass('fa-heart-o').addClass('fa-heart');
            $(this).text("已收藏");
            $(this).css("color", "#ff5e76");
            heart.close = false;
        } else {
            $(this).removeClass('fa-heart').addClass('fa-heart-o');
            $(this).text("收藏");
            $(this).css("color", "#282f3c");
            heart.close = true;
        }
    });
    //当前用户点赞动态id
    $scope.tourIdLikeList = [];
    //当前用户收藏动态id
    $scope.tourIdCollList = [];
    //用户点赞记录
    $scope.showLikeList = function () {
        if (!token) {
            $scope.getAllDynamicsInfo();
        } else {
            //点赞动态列表id
            $http({
                method: 'get',
                url: app.netPath + '/dynamic/details/show/likes',
                headers: {'Authorization': token}
            }).then(function (res) {
                if (!res.data.error) {
                    for (var i = 0; i < res.data.data.length; i++) {
                        $scope.tourIdLikeList.push(res.data.data[i].likedynaId);
                    }
                }
                $scope.getAllDynamicsInfo();
            });
        }

    };
    //用户收藏记录
    $scope.showCollectionList = function () {
        if (!token) {
            $scope.showLikeList();
        } else {
            $http({
                method: 'get',
                url: app.netPath + '/collection/show',
                headers: {'Authorization': token}
            }).then(function (res) {
                if (!res.data.error) {
                    for (var i = 0; i < res.data.data.length; i++) {
                        $scope.tourIdCollList.push(res.data.data[i].collDynaid);
                    }
                }
                $scope.showLikeList();
            });
        }
    };

    //用户信息对象
    $scope.showCircle = false;
    $scope.userInfo = {};
    $scope.getPersonInfo = function () {
        if (!token) {
            $scope.words = "用户";
            $scope.userDetail = "个性签名。。。。"
        }
        if (token) {
            $http({
                method: 'get',
                url: app.netPath + '/users/details/show',
                headers: {'Authorization': token}
            }).then(function (res) {
                if (!res.data.error) {
                    $scope.userInfo = res.data.data;
                    console.log(res.data.data);

                    var avatarImg = {};

                    if (res.data.data.userAvatarAddress) {
                        avatarImg.imgAddress = app.netPath + '/resources/img/' + res.data.data.userAvatarAddress;
                        $scope.userInfo.avatarImg = avatarImg;
                    }
                    if (res.data.data.userDetail) {
                        $scope.userDetail = $scope.userInfo.userDetail;
                    }
                    if ($scope.userInfo.userNickName) {
                        $scope.words = $scope.userInfo.userNickName;
                    }

                }
                else {
                    $.toast(res.data.error + ',' + res.data.msg);
                }
            }, function () {
                $.toast('网络走丢了！')
            });


        }
    };
    $scope.page = 1;
    $scope.page2 = 1;
    $scope.page3 = 1;
    $scope.page4 = 1;
    $scope.dynamicsList = [];
    $scope.dynamicsList2 = [];
    $scope.dynamicsList3 = [];
    $scope.dynamicsList4 = [];

    //获得全部动态列表
    $scope.getAllDynamicsInfo = function () {
        $scope.dynamicsListTrue = 1;
        $scope.dynamicsList2True = 0;
        $scope.dynamicsList3True = 0;

        if ($scope.dynamicsList.length == 0) {
            //第一次请求
            $scope.page = 1;
        } else {
            $scope.page = ($scope.dynamicsList.length % 3 == 0 ? ($scope.dynamicsList.length / 3) + 1 : parseInt($scope.dynamicsList.length / 3) + 2);
        }
        // $scope.page = page ? page : 1;
        //
        // // 若该加载为初始化加载，即没有传入page参数
        // if (!page) {
        //     $scope.page = 1;
        // }
        $http({
            method: 'get',
            url: app.netPath + '/dynamic/showAll',
            params: {page: $scope.page}
        }).then(function (res) {
            var infiniteScroll = $('.infinite-scroll');
            var infiniteScrollPreloader = $('.infinite-scroll-preloader');
            if (!res.data.error) {
                console.log(res.data.data);
                for (var i = 0; i < res.data.data.length; i++) {
                    if (res.data.data[i].user.userAvatarAddress) {
                        res.data.data[i].user.userAvatarAddress = app.netPath + '/resources/img/' + res.data.data[i].user.userAvatarAddress;
                        app.buildImageUrl(res.data.data[i].user, 'userAvatarAddress', function () {
                            $scope.$digest();
                        });
                    }
                    //放置动态图片
                    if (res.data.data[i].tourdynaImg) {
                        //得到每条动态的图片数组
                        var dynamicImgs = app.getDynamicImg(res.data.data[i].tourdynaImg);
                        for (var j = 0; j < dynamicImgs.length; j++) {
                            dynamicImgs[j] = app.netPath + '/resources/taskImg/' + dynamicImgs[j];
                            app.buildImageUrl(dynamicImgs, j, function () {
                                $scope.$digest();
                            });
                        }
                        res.data.data[i].tourdynaImg = dynamicImgs;
                    }
                    for (var a = 0; a < $scope.tourIdLikeList.length; a++) {
                        if (res.data.data[i].tourdynaId == $scope.tourIdLikeList[a]) {
                            res.data.data[i].isLike = 1;
                        } else {

                        }
                    }
                    for (var a = 0; a < $scope.tourIdCollList.length; a++) {
                        if (res.data.data[i].tourdynaId == $scope.tourIdCollList[a]) {
                            res.data.data[i].isColl = 1;
                        } else {

                        }
                    }
                    console.log(res.data.data[i]);
                    var lat = res.data.data[i].positionX;
                    var lng = res.data.data[i].positionY;
                    res.data.data[i].distance = app.getGreatCircleDistance(lat, lng);
                    if (res.data.data[i].distance >= 1000) {
                        res.data.data[i].distance = (app.getGreatCircleDistance(lat, lng) / 1000).toFixed(2) + "千米";
                    } else {
                        res.data.data[i].distance = app.getGreatCircleDistance(lat, lng) + "米";
                    }
                    //将动态逐条存入（dynamicsList）数组
                    $scope.dynamicsList.push(res.data.data[i]);
                }
                // 启用无限加载事件
                $.attachInfiniteScroll(infiniteScroll);
                // 启用提示符
                infiniteScrollPreloader.show();
                var thispage = $scope.dynamicsList.length % 3 == 0 ? $scope.dynamicsList.length / 3 : $scope.dynamicsList.length / 3 + 1;
                if (res.data.allPage <= thispage) {
                    // 加载完毕，则注销无限加载事件，以防不必要的加载
                    $.detachInfiniteScroll(infiniteScroll);
                    // 删除加载提示符
                    infiniteScrollPreloader.hide();
                }

            }
            else {
                // $.toast(res.data.error + ',' + res.data.msg);
                // 删除加载提示符
                infiniteScrollPreloader.hide();
            }
            $scope.isOnloading = false;
        }, function () {
            $.toast('网络走丢了！')
        });

    };
    //获得关注动态列表
    $scope.getAllDynamicsInfo2 = function () {
        $scope.dynamicsList2True = 1;
        $scope.dynamicsListTrue = 0;
        $scope.dynamicsList3True = 0;
        if (!token) {
            //判断有无证书
            $.toast("请先登录");
            location.href = '#login';
            return;
        }
        if ($scope.dynamicsList2.length == 0) {
            //第一次请求
            $scope.page2 = 1;
        } else {
            $scope.page2 = ($scope.dynamicsList2.length % 3 == 0 ? ($scope.dynamicsList2.length / 3) + 1 : parseInt($scope.dynamicsList2.length / 3) + 2);
        }
        // $scope.page2 = page ? page : 1;
        //
        // // 若该加载为初始化加载，即没有传入page参数
        // if (!page) {
        //     $scope.page2 = 1;
        // }
        $http({
            method: 'get',
            url: app.netPath + '/dynamic/details/showAllFollow',
            headers: {'Authorization': token},
            params: {page: $scope.page2}
        }).then(function (res) {
            var infiniteScroll = $('.infinite-scroll');
            var infiniteScrollPreloader = $('.infinite-scroll-preloader');
            if (!res.data.error) {
                console.log(res.data.data);
                for (var i = 0; i < res.data.data.length; i++) {
                    if (res.data.data[i].user.userAvatarAddress) {
                        res.data.data[i].user.userAvatarAddress = app.netPath + '/resources/img/' + res.data.data[i].user.userAvatarAddress;
                        app.buildImageUrl(res.data.data[i].user, 'userAvatarAddress', function () {
                            $scope.$digest();
                        });
                    }
                    //放置动态图片
                    if (res.data.data[i].tourdynaImg) {
                        //得到每条动态的图片数组
                        var dynamicImgs = app.getDynamicImg(res.data.data[i].tourdynaImg);
                        for (var j = 0; j < dynamicImgs.length; j++) {
                            dynamicImgs[j] = app.netPath + '/resources/taskImg/' + dynamicImgs[j];
                            app.buildImageUrl(dynamicImgs, j, function () {
                                $scope.$digest();
                            });
                        }
                        res.data.data[i].tourdynaImg = dynamicImgs;
                    }
                    for (var a = 0; a < $scope.tourIdLikeList.length; a++) {
                        if (res.data.data[i].tourdynaId == $scope.tourIdLikeList[a]) {
                            res.data.data[i].isLike = 1;
                        } else {

                        }
                    }
                    for (var a = 0; a < $scope.tourIdCollList.length; a++) {
                        if (res.data.data[i].tourdynaId == $scope.tourIdCollList[a]) {
                            res.data.data[i].isColl = 1;
                        } else {

                        }
                    }
                    var lat = res.data.data[i].positionX;
                    var lng = res.data.data[i].positionY;
                    res.data.data[i].distance = app.getGreatCircleDistance(lat, lng);
                    if (res.data.data[i].distance >= 1000) {
                        res.data.data[i].distance = (app.getGreatCircleDistance(lat, lng) / 1000).toFixed(2) + "千米";
                    } else {
                        res.data.data[i].distance = app.getGreatCircleDistance(lat, lng) + "米";
                    }
                    //将动态逐条存入（dynamicsList2）数组
                    $scope.dynamicsList2.push(res.data.data[i]);
                }
                // 启用无限加载事件
                $.attachInfiniteScroll(infiniteScroll);
                // 启用提示符
                infiniteScrollPreloader.show();
                var thispage = $scope.dynamicsList2.length % 3 == 0 ? $scope.dynamicsList2.length / 3 : $scope.dynamicsList2.length / 3 + 1;
                if (res.data.allPage <= thispage) {
                    // 加载完毕，则注销无限加载事件，以防不必要的加载
                    $.detachInfiniteScroll(infiniteScroll);
                    // 删除加载提示符
                    infiniteScrollPreloader.hide();
                }

            }
            else {
                // $.toast(res.data.error + ',' + res.data.msg);
                // 删除加载提示符
                infiniteScrollPreloader.hide();
            }
            $scope.isOnloading = false;
        }, function () {
            $.toast('网络走丢了！')
        });

    };

    //获得最新动态列表
    $scope.getAllDynamicsInfo3 = function () {
        $scope.dynamicsList3True = 1;
        $scope.dynamicsList2True = 0;
        $scope.dynamicsListTrue = 0;
        if ($scope.dynamicsList3.length == 0) {
            //第一次请求
            $scope.page3 = 1;
        } else {
            $scope.page3 = ($scope.dynamicsList3.length % 3 == 0 ? ($scope.dynamicsList3.length / 3) + 1 : parseInt($scope.dynamicsList3.length / 3) + 2);

        }
        // $scope.page3 = page ? page : 1;
        // // 若该加载为初始化加载，即没有传入page参数
        // if (!page) {
        //     $scope.page3 = 1;
        // }
        $http({
            method: 'get',
            url: app.netPath + '/dynamic/showAllNew',
            params: {page: $scope.page3}
        }).then(function (res) {
            var infiniteScroll = $('.infinite-scroll');
            var infiniteScrollPreloader = $('.infinite-scroll-preloader');
            if (!res.data.error) {
                console.log(res.data.data);
                for (var i = 0; i < res.data.data.length; i++) {
                    if (res.data.data[i].user.userAvatarAddress) {
                        res.data.data[i].user.userAvatarAddress = app.netPath + '/resources/img/' + res.data.data[i].user.userAvatarAddress;
                        app.buildImageUrl(res.data.data[i].user, 'userAvatarAddress', function () {
                            $scope.$digest();
                        });
                    }
                    //放置动态图片
                    if (res.data.data[i].tourdynaImg) {
                        //得到每条动态的图片数组
                        var dynamicImgs = app.getDynamicImg(res.data.data[i].tourdynaImg);
                        for (var j = 0; j < dynamicImgs.length; j++) {
                            dynamicImgs[j] = app.netPath + '/resources/taskImg/' + dynamicImgs[j];
                            app.buildImageUrl(dynamicImgs, j, function () {
                                $scope.$digest();
                            });
                        }
                        res.data.data[i].tourdynaImg = dynamicImgs;
                    }
                    for (var a = 0; a < $scope.tourIdLikeList.length; a++) {
                        if (res.data.data[i].tourdynaId == $scope.tourIdLikeList[a]) {
                            res.data.data[i].isLike = 1;
                        } else {

                        }
                    }
                    for (var a = 0; a < $scope.tourIdCollList.length; a++) {
                        if (res.data.data[i].tourdynaId == $scope.tourIdCollList[a]) {
                            res.data.data[i].isColl = 1;
                        } else {

                        }
                    }
                    var lat = res.data.data[i].positionX;
                    var lng = res.data.data[i].positionY;
                    res.data.data[i].distance = app.getGreatCircleDistance(lat, lng);
                    if (res.data.data[i].distance >= 1000) {
                        res.data.data[i].distance = (app.getGreatCircleDistance(lat, lng) / 1000).toFixed(2) + "千米";
                    } else {
                        res.data.data[i].distance = app.getGreatCircleDistance(lat, lng) + "米";
                    }
                    //将动态逐条存入（dynamicsList3）数组
                    $scope.dynamicsList3.push(res.data.data[i]);
                }
                // 启用无限加载事件
                $.attachInfiniteScroll(infiniteScroll);
                // 启用提示符
                infiniteScrollPreloader.show();
                var thispage = $scope.dynamicsList3.length % 3 == 0 ? $scope.dynamicsList3.length / 3 : $scope.dynamicsList3.length / 3 + 1;
                if (res.data.allPage <= thispage) {
                    // 加载完毕，则注销无限加载事件，以防不必要的加载
                    $.detachInfiniteScroll(infiniteScroll);
                    // 删除加载提示符
                    infiniteScrollPreloader.hide();
                }

            }
            else {
                // $.toast(res.data.error + ',' + res.data.msg);
                // 删除加载提示符
                infiniteScrollPreloader.hide();
            }
            $scope.isOnloading = false;
        }, function () {
            $.toast('网络走丢了！')
        });

    };
    //获得距离最近的动态列表
    $scope.showNearestNews = function () {
        var infiniteScroll = $('.infinite-scroll');
        var infiniteScrollPreloader = $('.infinite-scroll-preloader');
        $http({
            method: 'get',
            url: app.netPath + '/dynamic/showNearestNews'
        }).then(function (res) {
            if (!res.data.error) {
                // 加载完毕，则注销无限加载事件，以防不必要的加载
                $.detachInfiniteScroll(infiniteScroll);
                // 删除加载提示符
                infiniteScrollPreloader.hide();
                $scope.dynamicsList4 = [];
                for (var i = 0; i < res.data.data.length; i++) {
                    if (res.data.data[i].user.userAvatarAddress) {
                        res.data.data[i].user.userAvatarAddress = app.netPath + '/resources/img/' + res.data.data[i].user.userAvatarAddress;
                        app.buildImageUrl(res.data.data[i].user, 'userAvatarAddress', function () {
                            $scope.$digest();
                        });
                    }
                    //放置动态图片
                    if (res.data.data[i].tourdynaImg) {
                        //得到每条动态的图片数组
                        var dynamicImgs = app.getDynamicImg(res.data.data[i].tourdynaImg);
                        for (var j = 0; j < dynamicImgs.length; j++) {
                            dynamicImgs[j] = app.netPath + '/resources/taskImg/' + dynamicImgs[j];
                            app.buildImageUrl(dynamicImgs, j, function () {
                                $scope.$digest();
                            });
                        }
                        res.data.data[i].tourdynaImg = dynamicImgs;
                    }
                    for (var a = 0; a < $scope.tourIdLikeList.length; a++) {
                        if (res.data.data[i].tourdynaId == $scope.tourIdLikeList[a]) {
                            res.data.data[i].isLike = 1;
                        } else {

                        }
                    }
                    for (var a = 0; a < $scope.tourIdCollList.length; a++) {
                        if (res.data.data[i].tourdynaId == $scope.tourIdCollList[a]) {
                            res.data.data[i].isColl = 1;
                        } else {

                        }
                    }
                    var lat = res.data.data[i].positionX;
                    var lng = res.data.data[i].positionY;
                    res.data.data[i].distance = app.getGreatCircleDistance(lat, lng);
                    // if (res.data.data[i].distance >= 1000) {
                    //     res.data.data[i].distance = (app.getGreatCircleDistance(lat, lng) / 1000).toFixed(2);
                    // } else {
                    //     res.data.data[i].distance = app.getGreatCircleDistance(lat, lng);
                    // }
                    //将动态逐条存入（dynamicsList3）数组
                    $scope.dynamicsList4.push(res.data.data[i]);
                }
                $scope.sort($scope.dynamicsList4);
                console.log($scope.dynamicsList4);
            }

        });
    };
    //点赞
    $scope.addLike = function (tourdynaId, index, type) {
        if (!token) {
            //判断有无证书
            $.toast("请先登录");
            location.href = '#login';
            return;
        } else {
            $http({
                method: 'get',
                url: app.netPath + '/dynamic/details/likeAdd',
                headers: {'Authorization': token},
                params: {tourdynaId: tourdynaId}
            }).then(function (res) {
                if (!res.data.error) {
                    if (type == 1) {
                        $scope.dynamicsList[index].isLike = 1;
                        $scope.dynamicsList[index].tourdynaLikeNum = $scope.dynamicsList[index].tourdynaLikeNum + 1;
                    }
                    if (type == 2) {
                        $scope.dynamicsList2[index].isLike = 1;
                        $scope.dynamicsList2[index].tourdynaLikeNum = $scope.dynamicsList2[index].tourdynaLikeNum + 1;
                    }
                    if (type == 3) {
                        $scope.dynamicsList3[index].isLike = 1;
                        $scope.dynamicsList3[index].tourdynaLikeNum = $scope.dynamicsList3[index].tourdynaLikeNum + 1;
                    }
                    if (type == 4) {
                        $scope.dynamicsList4[index].isLike = 1;
                        $scope.dynamicsList4[index].tourdynaLikeNum = $scope.dynamicsList4[index].tourdynaLikeNum + 1;
                    }
                } else {
                    // $.toast(res.data.error + ',' + res.data.msg);

                }
            });
        }
    };
    //取消点赞
    $scope.reduceLike = function (tourdynaId, index, type) {
        if (!token) {
            //判断有无证书
            $.toast("请先登录");
            // location.href = '#login';
            return;
        } else {
            $http({
                method: 'get',
                url: app.netPath + '/dynamic/details/likeReduce',
                headers: {'Authorization': token},
                params: {tourdynaId: tourdynaId}
            }).then(function (res) {
                if (!res.data.error) {
                    if (type == 1) {
                        $scope.dynamicsList[index].isLike = 0;
                        $scope.dynamicsList[index].tourdynaLikeNum = $scope.dynamicsList[index].tourdynaLikeNum - 1;
                    }
                    if (type == 2) {
                        $scope.dynamicsList2[index].isLike = 0;
                        $scope.dynamicsList2[index].tourdynaLikeNum = $scope.dynamicsList2[index].tourdynaLikeNum - 1;
                    }
                    if (type == 3) {
                        $scope.dynamicsList3[index].isLike = 0;
                        $scope.dynamicsList3[index].tourdynaLikeNum = $scope.dynamicsList3[index].tourdynaLikeNum - 1;
                    }
                    if (type == 4) {
                        $scope.dynamicsList4[index].isLike = 0;
                        $scope.dynamicsList4[index].tourdynaLikeNum = $scope.dynamicsList4[index].tourdynaLikeNum - 1;
                    }
                } else {
                    $.toast(res.data.error + ',' + res.data.msg);
                }
            });
        }
    };
    //添加收藏
    $scope.addCollection = function (tourdynaId, index, type) {
        if (!token) {
            //判断有无证书
            $.toast("请先登录");
            // location.href = '#login';
            return;
        } else {
            $http({
                method: 'get',
                url: app.netPath + '/collection/add',
                headers: {'Authorization': token},
                params: {tourdynaId: tourdynaId}
            }).then(function (res) {
                if (!res.data.error) {
                    if (type == 1) {
                        $scope.dynamicsList[index].isColl = 1;
                    }
                    if (type == 2) {
                        $scope.dynamicsList2[index].isColl = 1;
                    }
                    if (type == 3) {
                        $scope.dynamicsList3[index].isColl = 1;
                    }
                    if (type == 4) {
                        $scope.dynamicsList4[index].isColl = 1;
                    }
                } else {

                }
            });
        }
    };
    // //取消收藏
    // $scope.reduceCollection = function (tourdynaId, index, type) {
    //     if (!token) {
    //         //判断有无证书
    //         $.toast("请先登录");
    //         // location.href = '#login';
    //         return;
    //     } else {
    //         $http({
    //             method: 'get',
    //             url: app.netPath + '/collection/delete',
    //             headers: {'Authorization': token},
    //             params: {collIds: tourdynaId}
    //         }).then(function (res) {
    //             if (!res.data.error) {
    //                 if (type == 1) {
    //                     $scope.dynamicsList[index].isColl = 0;
    //                 }
    //                 if (type == 2) {
    //                     $scope.dynamicsList2[index].isColl = 0;
    //                 }
    //                 if (type == 3) {
    //                     $scope.dynamicsList3[index].isColl = 0;
    //                 }
    //             } else {
    //                 $.toast(res.data.error + ',' + res.data.msg);
    //             }
    //         });
    //     }
    // };
    //跳转otherPerson详情页
    $scope.GoToOtherUser = function (userId) {
        sessionStorage.setItem('OtherUserId', userId);
    };

    $scope.GoToReview = function (tourdynaId, index) {
        sessionStorage.setItem('tourdynaInfoId', tourdynaId);
        //记录下是从哪里进入的详情页面
        sessionStorage.setItem('homeIndex', index);
    };
    $scope.keyWord = '';
    $scope.saveKeyWord = function () {
        sessionStorage.setItem('keyword', $scope.keyWord);
    };
    //距离排序
    $scope.sort = function (arr) {
        for (var j = 0; j < arr.length - 1; j++) {
            //两两比较，如果前一个比后一个大，则交换位置。
            for (var i = 0; i < arr.length - 1 - j; i++) {
                if (arr[i].distance > arr[i + 1].distance) {
                    var temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }
        }
        for (var a = 0; a < arr.length; a++) {
            if (arr[a].distance >= 1000) {
                arr[a].distance = (arr[a].distance / 1000).toFixed(2) + "千米";
            } else {
                arr[a].distance = arr[a].distance + "米";
            }
        }
    }
});
